package com.chnbst.bstyun.controller.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.OperateImage;
import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.eos.Eos;
import com.chnbst.bstyun.model.pojo.AdminUser;
import com.chnbst.bstyun.model.pojo.Attach;
import com.chnbst.bstyun.model.pojo.Goods;
import com.chnbst.bstyun.model.pojo.GoodsFee;
import com.chnbst.bstyun.model.pojo.GoodsRelation;
import com.chnbst.bstyun.model.pojo.GoodsType;
import com.chnbst.bstyun.model.pojo.StaticData;
import com.chnbst.bstyun.model.vo.GoodsVo;
import com.chnbst.bstyun.model.vo.ProductVo;
import com.chnbst.bstyun.service.AttachService;
import com.chnbst.bstyun.service.GoodsFeeService;
import com.chnbst.bstyun.service.GoodsRelationService;
import com.chnbst.bstyun.service.GoodsService;
import com.chnbst.bstyun.service.GoodsTypeService;
import com.chnbst.bstyun.service.StaticDataService;

/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author WangXinLei
 *
 */
@Controller
@RequestMapping("/sysAdmin")
public class GoodsListAdminController {
	
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsTypeService goodsTypeService;
	@Autowired
	private StaticDataService staticDataService;
	@Autowired
	private GoodsFeeService goodsFeeService;
	@Autowired
	private AttachService attachService;
	@Autowired
	private Eos eos;
	@Autowired
	private GoodsRelationService goodsRelationService;
	
	/**
	 * 商品列表界面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/goodsList",method=RequestMethod.GET)
	public ModelAndView goodsList()throws Exception{
		return new ModelAndView("/admin/productManager/goodsList");
	}
	
	/**
	 * 商品发布界面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/goodsPublish",method=RequestMethod.GET)
	public ModelAndView goodsPublish()throws Exception{
		List<StaticData> industries = staticDataService.selectStaticDataByStaticDataCode("110000");
		List<StaticData> goodCategories = staticDataService.selectStaticDataByStaticDataCode("120000");
		List<StaticData> units = staticDataService.selectStaticDataByStaticDataCode("130000");
		List<GoodsType> goodsTypeList = goodsTypeService.selectGoodsType();
		List<GoodsFee> goodsFeeList = goodsFeeService.selectGoodsFeeList();
		List<Goods> goodsList = goodsService.selectAllGoods(new HashMap<String, Object>());
		ModelAndView mav = new ModelAndView();
		mav.addObject("industries", industries);
		mav.addObject("goodCategories", goodCategories);
		mav.addObject("units", units);
		mav.addObject("goodsTypeList",goodsTypeList);
		mav.addObject("goodsFeeList",goodsFeeList);
		mav.addObject("goodsList",goodsList);
		mav.setViewName("/admin/productManager/goodpublish");
		return mav;
	}
	
	/**
	 * Ajax 分页查询商品list
	 * @return 商品列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/goodsList/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsList(String page,String last,HttpServletRequest request)throws Exception{
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		String goodsName = request.getParameter("goodsName");
		String isPublish = request.getParameter("isPublish");
		String auditState = request.getParameter("auditState");
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}
		map.put("goodsName", goodsName);
		map.put("isPublish", isPublish);
		map.put("auditState", auditState);
		
		int totalRows = goodsService.selectGoodsCount(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "goods_num");
		map.put("sortOrder", "asc");
		
		List<GoodsVo> goodsList = goodsService.selectGoods(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("goodsList", goodsList);
		resultMap.put("adminUser", request.getSession().getAttribute("adminUser"));
		
		return resultMap;
	}
	
	/**
	 * 根据ID查询商品的详细信息
	 * @return 商品详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/goodsDetail/{goodsId}",method=RequestMethod.GET)
	public ModelAndView goodsDetail(@PathVariable String goodsId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		//加载商品的详细信息
		GoodsVo goodsInfo = goodsService.selectGoodsVoByGoodsId(goodsId);
		Goods goodsTemp = goodsService.selectByGoodsId(goodsInfo.getGoodsRalateGoods());
		String product = "";
		if(goodsTemp != null) {
			product = goodsTemp.getGoodsName();
		}
		//加入的产品查询
		String proNames = "";
		String productNums = "";
		List<GoodsRelation> rList = goodsRelationService.selectByGoodsId(goodsId);
		for (GoodsRelation goodsRelation : rList) {
			String productName = goodsRelation.getProductName();
			String productNum = goodsRelation.getProductNum();
			if(proNames.equals("")){
				proNames += productName;
				productNums += productNum;
			}else{
				proNames += ","+productName;
				productNums += ","+productNum;
			}
		}
		
		mav.addObject("goodsInfo", goodsInfo);
		mav.addObject("product", product);
		mav.addObject("proNames", proNames);
		mav.addObject("productNums", productNums);
		mav.setViewName("/admin/productManager/goodsDetail");
		
		return mav;
	}
	
	/**
	 * 编辑商品页面
	 * @return 商品编辑页面
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/updateGoods/{goodsId}",method=RequestMethod.GET)
	public ModelAndView updateGoods(@PathVariable String goodsId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		//加载商品的详细信息
		GoodsVo goodsInfo = goodsService.selectGoodsVoByGoodsId(goodsId);
		
		List<StaticData> industries = staticDataService.selectStaticDataByStaticDataCode("110000");
		List<StaticData> goodCategories = staticDataService.selectStaticDataByStaticDataCode("120000");
		List<StaticData> units = staticDataService.selectStaticDataByStaticDataCode("130000");
		List<GoodsType> goodsTypeList = goodsTypeService.selectGoodsType();
		List<GoodsFee> goodsFeeList = goodsFeeService.selectGoodsFeeList();
		List<Goods> goodsList = goodsService.selectAllGoods(new HashMap<String, Object>());
		List<Attach> attachs = new ArrayList<Attach>();
		String[] str = goodsInfo.getAttachIds().split("\\|");
		for (int i = 0; i < str.length; i++) {
			Attach attach = attachService.selectAttachByAttachId(Integer.valueOf(str[i]));
			attachs.add(attach);
		}
		
		//加入的产品查询
		String proNames = "";
		String productNums = "";
		List<GoodsRelation> rList = goodsRelationService.selectByGoodsId(goodsId);
		for (GoodsRelation goodsRelation : rList) {
			String productName = goodsRelation.getProductName();
			String productNum = goodsRelation.getProductNum();
			if(proNames.equals("")){
				proNames += productName;
				productNums += productNum;
			}else{
				proNames += ","+productName;
				productNums += ","+productNum;
			}
		}
		
		mav.addObject("proNames", proNames);
		mav.addObject("productNums", productNums);
		mav.addObject("industries", industries);
		mav.addObject("goodCategories", goodCategories);
		mav.addObject("units", units);
		mav.addObject("goodsTypeList",goodsTypeList);
		mav.addObject("goodsFeeList",goodsFeeList);
		mav.addObject("goods", goodsInfo);
		mav.addObject("attachs", attachs);
		mav.addObject("goodsList", goodsList);
		mav.setViewName("/admin/productManager/goodpublish");
		return mav;
	}
	
	/**
	 * 新增、编辑商品
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/goodsListAdmin/addGoods",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsPublish(Goods goods,String categoryproes,String categoryproes_ids,HttpServletRequest request)throws Exception{
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		Map<String, Object> map = new HashMap<String, Object>();
		boolean isSuccess = false;
		Integer auditState = Integer.valueOf(request.getParameter("auditState"));
		
		goods.setUpdateId(adminUser.getAdminId());
		goods.setUpdateTime(new Date());
		goods.setAuditState(auditState);
		goods.setIsPublish(0);
		goods.setIsDelete(0);
		String goodsId = goods.getGoodsId();
		if(SignUtil.isEmpty(goodsId)){
			goods.setCreateId(adminUser.getAdminId());
			goods.setCreateTime(new Date());
			isSuccess = goodsService.insertGoods(goods);
			
			Goods goodTemp = goodsService.selectGoodsById(goods.getId());
			goods.setGoodsId(goodTemp.getGoodsId());
		}else{
			Goods goodsTmp = goodsService.selectByGoodsId(goodsId);
			if(!goodsTmp.getAttachIds().equals(goods.getAttachIds())) {
				goods.setAttachIds(goodsTmp.getAttachIds()+"|"+goods.getAttachIds());
			}
			isSuccess = goodsService.updateGoods(goods);
		}
		
		//先将商品和产品的关系解除
		goodsRelationService.deleteGoodsRelation(goods.getGoodsId());
		//将所选择产品保存到数据库
		String[] goodsRelationNumList = categoryproes_ids.split(",");
		String[] goodsRelationNameList = categoryproes.split(",");
		for(int i=0;i<goodsRelationNumList.length;i++){
			String proNum = goodsRelationNumList[i];
			String proName = goodsRelationNameList[i];
			GoodsRelation goodsRelation = new GoodsRelation();
			goodsRelation.setCreateId(adminUser.getAdminId());
			goodsRelation.setCreateTime(new Date());
			goodsRelation.setUpdateId(adminUser.getAdminId());
			goodsRelation.setUpdateTime(new Date());
			goodsRelation.setIsValid(1);
			goodsRelation.setProductName(proName);
			goodsRelation.setProductNum(proNum);
			goodsRelation.setGoodsId(goods.getGoodsId());
			goodsRelationService.insertGoodsRelation(goodsRelation);
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 已保存商品申请发布 
	 * @return 商品列表
	 */
	@RequestMapping(value="/operate/goodsListAdmin/goodsApplyPublish",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsApplyPublish(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		boolean isSuccess = false;
		String[] goodsids = request.getParameter("ids").split(","); 
		for (String goodsid : goodsids) {
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("goodsId", goodsid);
			Goods goods = goodsService.selectByCondition(map1);
			//只有已保存的商品才能申请发布
			if(goods.getAuditState() == 0) {
				goods.setUpdateId(adminUser.getAdminId());
				goods.setUpdateTime(new Date());
				goods.setAuditState(1);
				isSuccess = goodsService.updateGoods(goods);
			}else{
				map.put("message", "选中商品不符合申请发布要求，请重新选择！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 删除商品
	 * @return 商品列表
	 */
	@RequestMapping(value="/operate/goodsListAdmin/deleteGoods",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteGoods(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		String goodsid = request.getParameter("ids");    
		boolean isSuccess = false;
		if(goodsid.contains(",")) {
			String[] goodsIds = goodsid.split(",");
			for(int i=0;i<goodsIds.length;i++){
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("goodsId", goodsIds[i]);
				Goods goods = goodsService.selectByCondition(map1);
				//判断 如果是已上架的商品不能删除
				if(goods.getIsPublish() == null || goods.getIsPublish() != 1) {
					goods.setUpdateId(adminUser.getAdminId());
					goods.setUpdateTime(new Date());
					goods.setIsDelete(1);
					goods.setIsPublish(0);
					
					isSuccess = goodsService.updateGoods(goods);
					map.put("message", "删除成功！！");
				}else{
					map.put("message", "选中商品为已上架商品，不能删除！！");
				}
			}
		}else {
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("goodsId", goodsid);
			Goods goods = goodsService.selectByCondition(map1);
			//判断 如果是已上架的商品不能删除
			if(goods.getIsPublish() == null || goods.getIsPublish() != 1) {
				goods.setUpdateId(adminUser.getAdminId());
				goods.setUpdateTime(new Date());
				goods.setIsDelete(1);
				goods.setIsPublish(0);
				
				isSuccess = goodsService.updateGoods(goods);
				map.put("message", "删除成功！！");
			}else{
				map.put("message", "选中商品为已上架商品，不能删除！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 商品审核
	 * @return 商品列表
	 */
	@RequestMapping(value="/operate/goodsListAdmin/goodsAudit",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsAudit(String auditState,String reason, HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		
		String goodsid = request.getParameter("ids");    
		boolean isSuccess = false;
		if(goodsid.contains(",")) {
			String[] goodsIds = goodsid.split(",");
			for(int i=0;i<goodsIds.length;i++){
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("goodsId", goodsIds[i]);
				Goods goods = goodsService.selectByCondition(map1);
				//判断 只有待审核的商品才能审核
				if(goods.getAuditState() == 1) {
					goods.setUpdateId(adminUser.getAdminId());
					goods.setUpdateTime(new Date());
					//如果审核通过，则商品直接发布
					if("3".equals(auditState)){
						goods.setAuditState(3);
						goods.setPublishTime(new Date());
						goods.setReason(reason);
						goods.setIsPublish(1);
					}else if("2".equals(auditState)){
						goods.setAuditState(2);
						goods.setReason(reason);
					}
					isSuccess = goodsService.updateGoods(goods);
					map.put("message", "审核成功！！");
				}else{
					map.put("message", "选中商品为未申请发布或已审核商品，请重新选择！！");
				}
			}
		}else {
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("goodsId", goodsid);
			Goods goods = goodsService.selectByCondition(map1);
			//判断 只有待审核的商品才能审核
			if(goods.getAuditState() == 1) {
				goods.setUpdateId(adminUser.getAdminId());
				goods.setUpdateTime(new Date());
				//如果审核通过，则商品直接发布
				if("3".equals(auditState)){
					goods.setAuditState(3);
					goods.setReason(reason);
					goods.setPublishTime(new Date());
					goods.setIsPublish(1);
				}else if("2".equals(auditState)){
					goods.setAuditState(2);
					goods.setReason(reason);
				}
				isSuccess = goodsService.updateGoods(goods);
				map.put("message", "审核成功！！");
			}else{
				map.put("message", "选中商品为未申请发布或已审核商品，请重新选择！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 商品上架  
	 * @return 商品列表
	 */
	@RequestMapping(value="/operate/goodsListAdmin/goodsOnline",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsOnline(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		String goodsid = request.getParameter("ids");    
		boolean isSuccess = false;
		if(goodsid.contains(",")) {
			String[] goodsIds = goodsid.split(",");
			for(int i=0;i<goodsIds.length;i++){
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("goodsId", goodsIds[i]);
				Goods goods = goodsService.selectByCondition(map1);
				//判断 只有审核状态是已通过的商品才能上架
				if(goods.getAuditState() == 3) {
					goods.setUpdateId(adminUser.getAdminId());
					goods.setUpdateTime(new Date());
					goods.setIsPublish(1);
					
					isSuccess = goodsService.updateGoods(goods);
					map.put("message", "上架成功！！");
				}else{
					map.put("message", "上架失败！！");
				}
			}
		}else {
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("goodsId", goodsid);
			Goods goods = goodsService.selectByCondition(map1);
			//判断 只有审核状态是已通过的商品才能上架
			if(goods.getAuditState() == 3) {
				goods.setUpdateId(adminUser.getAdminId());
				goods.setUpdateTime(new Date());
				goods.setIsPublish(1);
				
				isSuccess = goodsService.updateGoods(goods);
				map.put("message", "上架成功！！");
			}else{
				map.put("message", "上架失败！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 商品下架 
	 * @return 商品列表
	 */
	@RequestMapping(value="/operate/goodsListAdmin/goodsOffline",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goodsOffline(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		String goodsid = request.getParameter("ids");    
		boolean isSuccess = false;
		if(goodsid.contains(",")) {
			String[] goodsIds = goodsid.split(",");
			for(int i=0;i<goodsIds.length;i++){
				Map<String, Object> map1 = new HashMap<String, Object>();
				map1.put("goodsId", goodsIds[i]);
				Goods goods = goodsService.selectByCondition(map1);
				//判断 只有审核状态是已通过的商品才能下架
				if(goods.getAuditState() == 3) {
					goods.setUpdateId(adminUser.getAdminId());
					goods.setUpdateTime(new Date());
					goods.setIsPublish(2);
					
					isSuccess = goodsService.updateGoods(goods);
					map.put("message", "下架成功！！");
				}else{
					map.put("message", "下架失败！！");
				}
			}
		}else {
			Map<String, Object> map1 = new HashMap<String, Object>();
			map1.put("goodsId", goodsid);
			Goods goods = goodsService.selectByCondition(map1);
			//判断 只有审核状态是已通过的商品才能上架
			if(goods.getAuditState() == 3) {
				goods.setUpdateId(adminUser.getAdminId());
				goods.setUpdateTime(new Date());
				goods.setIsPublish(2);
				
				isSuccess = goodsService.updateGoods(goods);
				map.put("message", "下架成功！！");
			}else{
				map.put("message", "下架失败！！");
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
	
	/**
	 * ajax请求 图片裁剪 
	 * @return map
	 * @throws IOException 
	 */
	@RequestMapping(value="/operate/goodsListAdmin/cutImg",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> cutImg(String url,int w,int h,int x,int y,int attachType,HttpServletRequest request) throws IOException{
		Map<String, Object> map = new HashMap<String, Object>();
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute("adminUser");
		//文件保存目录路径
		String savePath = request.getSession().getServletContext().getRealPath("/");
		
		String newFileName = OperateImage.cut(savePath+url, x, y, w, h);
		String saveUrl = url.substring(0, url.lastIndexOf("/")+1)+newFileName;
		
		//保存至附件表中
		Attach attach = new Attach();
		attach.setAttachName(newFileName);
		attach.setAttachPath(saveUrl);
		attach.setAttachType(attachType);
		attach.setCreateTime(new Date());
		attach.setUserId(adminUser.getAdminId());
		
		boolean b = attachService.insertAttach(attach);
		if(b) {
			map.put("attachId", attach.getAttachId());
		}
		map.put("saveUrl", saveUrl);
		return map;
	}
	
	
	/**
	 * @return 到portal处查询数据
	 * @throws UnsupportedEncodingException 
	 * @throws Exception
	 */
	@RequestMapping(value="/goodsListAdmin/selectProductByPortal",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> selectProductByPortal(HttpServletRequest request)throws Exception{
		boolean isOk = false;
		String product = eos.getProducts();
		ObjectMapper objectMapper = new ObjectMapper();
		ProductVo[] goodsList = objectMapper.readValue(product, ProductVo[].class);
		Map<String, Object> map = new HashMap<String, Object>();
		if(goodsList.length > 0){
			isOk = true;
		}
		map.put("isOk", isOk);
		map.put("goodsList", goodsList);
		return map;
	}
}
